using System;
using System.IO;
// Microsoft.Extensions.Logging 移除，避免与自定义LogLevel冲突
using ExcelTemplateEngine.Configuration;
using ExcelTemplateEngine.Infrastructure.Logging;
using ExcelTemplateEngine.Infrastructure.Performance;
using ExcelTemplateEngine.Infrastructure.DependencyInjection;

namespace ExcelTemplateEngine.Tests.Infrastructure
{
    /// <summary>
    /// 测试基类 - 为所有测试提供公共的基础设施和工具
    /// </summary>
    public abstract class TestBase : IDisposable
    {
        protected ITemplateEngineLogger Logger { get; private set; } = null!;
        protected IPerformanceMonitor PerformanceMonitor { get; private set; } = null!;
        protected IServiceContainer ServiceContainer { get; private set; } = null!;
        protected ITemplateEngineConfiguration Configuration { get; private set; } = null!;
        protected string TestOutputDirectory { get; private set; } = null!;
        
        private bool _disposed = false;
        
        protected TestBase()
        {
            InitializeTestInfrastructure();
        }
        
        /// <summary>
        /// 初始化测试基础设施
        /// </summary>
        private void InitializeTestInfrastructure()
        {
            // 创建测试输出目录
            TestOutputDirectory = Path.Combine(Path.GetTempPath(), "ExcelTemplateEngine.Tests", Guid.NewGuid().ToString());
            Directory.CreateDirectory(TestOutputDirectory);
            
            // 创建测试配置
            Configuration = new ConfigurationBuilder()
                .WithDebugMode(true)
                .WithTempDirectory(TestOutputDirectory)
                .WithPerformanceMonitoring(true, TimeSpan.FromSeconds(1))
                .Build();
            
            // 创建日志记录器
            Logger = new DefaultLogger("TestLogger", ExcelTemplateEngine.Infrastructure.Logging.LogLevel.Debug);
            
            // 创建性能监控器
            PerformanceMonitor = new DefaultPerformanceMonitor(Logger, Configuration.Performance);
            
            // 创建服务容器
            ServiceContainer = new SimpleServiceContainer();
            RegisterServices();
            
            Logger.LogInformation($"Test infrastructure initialized for {GetType().Name}");
        }
        
        /// <summary>
        /// 注册测试服务
        /// </summary>
        protected virtual void RegisterServices()
        {
            ServiceContainer.RegisterSingleton<ITemplateEngineConfiguration>(Configuration);
            ServiceContainer.RegisterSingleton<ITemplateEngineLogger>(Logger);
            ServiceContainer.RegisterSingleton<IPerformanceMonitor>(PerformanceMonitor);
        }
        
        /// <summary>
        /// 创建测试用的临时文件路径
        /// </summary>
        protected string CreateTempFilePath(string fileName)
        {
            return Path.Combine(TestOutputDirectory, fileName);
        }
        
        /// <summary>
        /// 创建测试用的Excel文件路径
        /// </summary>
        protected string CreateTempExcelPath(string? fileName = null)
        {
            fileName ??= $"test_{Guid.NewGuid():N}.xlsx";
            if (!fileName.EndsWith(".xlsx"))
                fileName += ".xlsx";
                
            return CreateTempFilePath(fileName);
        }
        
        /// <summary>
        /// 记录测试操作的性能
        /// </summary>
        protected T MeasurePerformance<T>(string operationName, Func<T> operation)
        {
            using var scope = PerformanceMonitor.BeginOperation(operationName);
            try
            {
                var result = operation();
                scope.SetResult(true);
                return result;
            }
            catch (Exception ex)
            {
                scope.SetResult(false, ex.Message);
                throw;
            }
        }
        
        /// <summary>
        /// 记录异步测试操作的性能
        /// </summary>
        protected async Task<T> MeasurePerformanceAsync<T>(string operationName, Func<Task<T>> operation)
        {
            using var scope = PerformanceMonitor.BeginOperation(operationName);
            try
            {
                var result = await operation();
                scope.SetResult(true);
                return result;
            }
            catch (Exception ex)
            {
                scope.SetResult(false, ex.Message);
                throw;
            }
        }
        
        /// <summary>
        /// 记录测试操作的性能（无返回值）
        /// </summary>
        protected void MeasurePerformance(string operationName, Action operation)
        {
            using var scope = PerformanceMonitor.BeginOperation(operationName);
            try
            {
                operation();
                scope.SetResult(true);
            }
            catch (Exception ex)
            {
                scope.SetResult(false, ex.Message);
                throw;
            }
        }
        
        /// <summary>
        /// 获取性能统计信息
        /// </summary>
        protected PerformanceStatistics GetPerformanceStatistics()
        {
            return PerformanceMonitor.GetStatistics();
        }
        
        /// <summary>
        /// 重置性能统计
        /// </summary>
        protected void ResetPerformanceStatistics()
        {
            PerformanceMonitor.Reset();
        }
        
        /// <summary>
        /// 验证文件是否存在且大小合理
        /// </summary>
        protected void AssertFileExists(string filePath, long? minSize = null, long? maxSize = null)
        {
            Assert.True(File.Exists(filePath), $"File does not exist: {filePath}");
            
            var fileInfo = new FileInfo(filePath);
            if (minSize.HasValue)
            {
                Assert.True(fileInfo.Length >= minSize.Value, 
                    $"File size {fileInfo.Length} is less than minimum {minSize.Value}");
            }
            
            if (maxSize.HasValue)
            {
                Assert.True(fileInfo.Length <= maxSize.Value, 
                    $"File size {fileInfo.Length} is greater than maximum {maxSize.Value}");
            }
        }
        
        /// <summary>
        /// 清理资源
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed && disposing)
            {
                try
                {
                    // 记录测试结束
                    Logger?.LogInformation($"Test cleanup started for {GetType().Name}");
                    
                    // 输出性能统计
                    var stats = PerformanceMonitor?.GetStatistics();
                    if (stats != null && stats.TotalOperations > 0)
                    {
                        Logger?.LogInformation($"Performance Summary: {stats.TotalOperations} operations");
                        foreach (var op in stats.Operations.Values.Take(5)) // 只显示前5个
                        {
                            Logger?.LogInformation($"  {op.OperationName}: {op.Count} times, avg {op.AverageDuration.TotalMilliseconds:F2}ms");
                        }
                    }
                    
                    // 清理临时文件
                    if (Directory.Exists(TestOutputDirectory))
                    {
                        try
                        {
                            Directory.Delete(TestOutputDirectory, true);
                            Logger?.LogDebug($"Cleaned up test directory: {TestOutputDirectory}");
                        }
                        catch (Exception ex)
                        {
                            Logger?.LogWarning($"Failed to cleanup test directory: {TestOutputDirectory}. Error: {ex.Message}");
                        }
                    }
                }
                catch (Exception ex)
                {
                    // 避免在Dispose中抛出异常
                    System.Diagnostics.Debug.WriteLine($"Error during test cleanup: {ex}");
                }
                
                _disposed = true;
            }
        }
    }
}